*** PROGRAM FOR OUTPUTTING FIXED EFFECTS REGRESSIONS *** 

cap program drop myoutreg
program myoutreg
	* Description: Outreg2 with stars, p-value from F-test, fixed effect indicators, time trends(optional), leads test (optional). Run after every regression
	
	* Variables
	* file: File name; fe1 to fe5: Fixed Effects, currently only up to 5; trend: dimensionality of trends
	* keep: Variables to keep; lead: Pass Leads Test(y/n) 
	* extra: Extra addtext options (e.g. extra("Factors","`nof'")
	* title: Title of table
	* extra_commands: Extra outreg2 options 

	syntax [if] [in] [, file(str) fe1(str) fe2(str) fe3(str) fe4(str) fe5(str) trend(str) keep(varlist) lead(str) extra(str) title(str) extra_commands(str)]
		
	`if' {
	
		* Make all strings proper 
		foreach i of numlist 1/5 {
			local pfe`i'=proper("`fe`i''")
		}
		local ptrend=proper("`trend'") 
		local plead=proper("`lead'")
		local starkeep "append excel alpha (0.01 , 0.05 , 0.1) symbol (***,**,*) keep(`keep')"
		if "`title'"!="" local ctitle "ctitle(`title')" 
		* F-stat
		local fmodel = string(Ftail(`e(df_m)',`e(df_r)',`e(F)'), "%12.3f")
		
		* String up FEs for output 
		foreach i of numlist 1/5 {
			if "`fe`i''"!="" local feopt `feopt' `", `"`pfe`i'' FE"', X "'
		}
		
		* Check for trend option 
		if "`trend'"=="" local trendopt ""
		if "`trend'"!="" local trendopt `", "Time Trend", `trend' "'
		
		* Check for lead option 
		if "`lead'"=="" local leadopt ""
		if "`lead'"!="" local leadopt `", "Pass leads test?", `plead' "'
		
		* Check for extra options 
		if "`extra'"=="" local extraopt ""
		if "`extra'"!="" local extraopt `", `extra'"'
		
		* Check for number of units (only applicable for unit FE, or else generates df of first FE)
		if "`e(K1)'"!="" local unitopt `", "Number of units", `e(K1)' "'
		* CHeck for number of clusters
		if "`e(N_clust)'"!="" local clusteropt `", "Number of clusters", `e(N_clust)' "'
		
		* Outreg2 with options
		outreg2 using "`file'.xml", `starkeep' addtext("Prob > F", `fmodel' `feopt' `unitopt' `clusteropt' `leadopt' `trendopt' `extraopt') `ctitle' `extra_commands'   
	
	}
	
end